<template>
  <div></div>
</template>

<script>
import api from "@/api/index"
import store from "@/store";
import qs from "qs";
import {Base64} from 'js-base64'
import theme from "@/utils/theme";
export default {

  name: "Login",
  data() {
    return {
      otherQuery:"",
      redirect: undefined,
    };
  },
  created() {
    this.getSiteInfo()
    let code = this.getQueryString("code")
    let redirect = this.getQueryString("redirect")
    let decodeRedirect = redirect?Base64.decode(redirect):"";
    if (code) {
      let data = {
        redirect:redirect,
        ...this.otherQuery
      };
      store.dispatch("user/loginOauth", data).then(() => {
        this.$router.push({
          path: this.redirect || "/",
          query: this.otherQuery
        });
      })
    } else {
      let params =  this.otherQuery?qs.stringify(this.otherQuery):""
      let url = this.redirect
      if(params)url = `${this.redirect}?${params}`
      api.getLoginUrl({redirect:url}).then(res=>{
        window.location.href = res.data.url;
      })
    }
  },
  watch: {
    $route: {
      handler: function(route) {
        const query = route.query;
        if (query) {
          this.redirect = query.redirect;
          this.otherQuery = this.getOtherQuery(query);
        }
      },
      immediate: true
    }
  },
  methods: {
    getSiteInfo() {
      store.dispatch('baseSettings/getSiteInfo').then(res=>{
        this.info = res
        theme.renderingTheme(this.info.theme)
      })
    },
    getOtherQuery(query) {
      return Object.keys(query).reduce((acc, cur) => {
        if (cur !== "redirect") {
          acc[cur] = query[cur];
        }
        return acc;
      }, {});
    },
    getQueryString(name) {
      let reg = `(^|&)${name}=([^&]*)(&|$)`
      let r = window.location.search.substr(1).match(reg);
      if (r != null) return unescape(r[2]);
      return null;
    }
  }
};
</script>

<style lang="scss"></style>
